import {
  SET_TMP_PALLET_LIST,
  SET_TMP_PALLET_CURRENT_PALLET,
  CLEAR_TMP_PALLET_OPS_FORM,
  SET_TMP_PALLET_OPS_FORM,
  SET_TMP_PALLET_ITEM_DETAILS,
  SET_TMP_PALLET_BARCODE_DETAILS,
  DEL_TMP_PALLET_BARCODE,
  SET_TMP_PALLET_DATA_ID
} from "./action-types";

const initialState = {
  currentPallet: null,

  palletList: [],
  palletListOffset: 0,

  opsFormData: null,

  palletDataId: null,
  itemDetails: [],
  barcodeDetails: [],
};

const handlePalletList = (state, payload) => {
  let { items, offset } = payload;
  if (items.length === 0 && offset === 0) {
    return { ...state, palletList: [], palletListOffset: 0 };
  } else {
    return {
      ...state,
      palletList: state.palletList.concat(items),
      palletListOffset: offset
    };
  }
};

const handleDelBarcode = (state, payload) => {
  return {
    ...state,
    barcodeDetails: state.barcodeDetails.filter((i) => i.id !== payload.id),
  };
};

const data = (state = initialState, action) => {
  switch (action.type) {
    case SET_TMP_PALLET_LIST:
      return handlePalletList(state, action.payload);
    case SET_TMP_PALLET_CURRENT_PALLET:
      return { ...state, currentPallet: action.payload };
    case CLEAR_TMP_PALLET_OPS_FORM:
      return { ...state, opsFormData: null, palletDataId: null };
    case SET_TMP_PALLET_OPS_FORM:
      return { ...state, opsFormData: action.payload };
    case SET_TMP_PALLET_ITEM_DETAILS:
      return { ...state, itemDetails: action.payload.items };
    case SET_TMP_PALLET_BARCODE_DETAILS:
      return { ...state, barcodeDetails: action.payload.items };
    case DEL_TMP_PALLET_BARCODE:
      return handleDelBarcode(state, action.payload);
    case SET_TMP_PALLET_DATA_ID:
      return { ...state, palletDataId: action.payload };
    default:
      return state;
  }
};

export default data;
